#ifndef TOOLS_EVENTLOOP_H
#define TOOLS_EVENTLOOP_H

#include "Variant.h"
#include "Timer.h"
#include "DataTime.h"
#include "BlockQueue.h"
#include "ThreadPool.h"
#include <functional>
#include <memory>
#include <unordered_map>
#include <mutex>
#include <vector>
#include <atomic>
#include <queue>
#include <set>
#include <condition_variable>

namespace Tool
{

/*
* 1. 基础类型定义
* 2. 事件队列（线程安全）
* 3. 事件处理器（回调绑定） EventHandler 
* 4. 事件循环核心
*/
enum class EventType : uint8_t
{
    Message = 0,        // 消息队列事件
    Timer,              // 定时器事件
    IO,                 // IO事件（如socket可读可写）
    SignalSlot,         // 信号槽事件
    UserRole = 100      // 自定义事件
};

ExportAPI EventType& operator++(EventType& type);
ExportAPI EventType operator+(EventType type, int n);

enum class EventPriority : uint8_t
{
    Low = 0,
    Normal,
    High,
    Critical        // 紧急
};

struct ExportAPI Event
{
    EventType       type;
    EventPriority   priority;
    DataTime        timestamp;          // 事件产生时间戳
    Variant         data;               // 事件携带的数据
    int64_t         eventId;            // 事件ID
    void*           userData;           // 用户自定义数据
    bool            isOneShot;          // 是否一次性事件
    
    Event(EventType t, EventPriority p = EventPriority::Normal, Variant d = Variant());
    virtual ~Event() = default;
};

struct ExportAPI MessageEvent : Event 
{
    int64_t         msg_id;
    std::string content;
    
    MessageEvent(int64_t id);
    MessageEvent(int64_t id, const std::string& cnt, EventPriority p = EventPriority::Normal);
};

struct ExportAPI IOEvent : Event
{
    int socketFd;
    uint32_t events;  // 例如：EPOLLIN, EPOLLOUT等
    
    IOEvent(int fd, uint32_t ev, EventPriority p = EventPriority::Normal);
};

struct ExportAPI TimerEvent : Event
{
    int64_t     timerId;
    uint64_t    intervalMs;  // 毫秒
    
    TimerEvent(int64_t id, uint64_t interval, EventPriority p = EventPriority::Normal);
};

// 优先级事件队列，确保高优先级事件先处理
class ExportAPI PriorityEventQueue
{
private:
    struct EventComparator
    {
        bool operator()(const std::shared_ptr<Event>& a, const std::shared_ptr<Event>& b) const
        {
            if (a->priority != b->priority)
            {
                return a->priority < b->priority;
            }
            return a->timestamp > b->timestamp;
        }
    };

    std::priority_queue<std::shared_ptr<Event>, std::vector<std::shared_ptr<Event>>, EventComparator> m_queue;
    mutable std::mutex m_mutex;
    std::condition_variable m_cv;
    bool m_stopped = false;

public:
    PriorityEventQueue() = default;
    ~PriorityEventQueue() = default;

    PriorityEventQueue(const PriorityEventQueue&) = delete;
    PriorityEventQueue& operator=(const PriorityEventQueue&) = delete;

    void Push(std::shared_ptr<Event> event);
    bool TryPop(std::shared_ptr<Event>& out, std::chrono::milliseconds timeout);
    void Stop();
    bool IsEmpty() const;
};

using EventHandlerFunc = std::function<void(std::shared_ptr<Event>)>;

class ExportAPI EventHandler 
{
public:

    EventHandler() = default;
    ~EventHandler() = default;
    using HandlerId = uint64_t;

    HandlerId RegisterHandler(EventType type, EventHandlerFunc func);
    bool RemoveHandler(EventType type, HandlerId id);
    void HandleEvent(std::shared_ptr<Event> event);

private:
    std::unordered_map<EventType, std::vector<std::pair<HandlerId, EventHandlerFunc>>> m_handlers;
    std::mutex m_mutex;
    std::atomic<HandlerId> m_nextHandlerId{1}; // 从1开始，0为无效ID
};

// 高性能定时器
class ExportAPI HighResTimer
{
public:
    HighResTimer();
    ~HighResTimer();
    
    uint64_t GetCurrentTimeMs() const;
    int64_t AddTimer(uint64_t intervalMs, std::function<void(int64_t)> callback, void* userData = nullptr, bool isOneShot = false);
    bool RemoveTimer(int64_t timerId);
    void Update();  // 由事件循环调用，检查并触发到期的定时器
    uint64_t GetNextExpirationTime(); // 获取下一个定时器的到期时间
    
private:
    struct Timer
    {
        int64_t id;
        uint64_t intervalMs;
        uint64_t nextRunTime;
        std::function<void(int64_t)> callback;
        void* userData;
        bool isOneShot;
        
        bool operator<(const Timer& other) const
        {
            if (nextRunTime != other.nextRunTime)
            {
                return nextRunTime < other.nextRunTime;
            }
            return id < other.id;
        }
    };
    
    std::set<Timer> m_timers;    // 按时间排序的定时器集合
    std::mutex m_mutex;
    std::atomic<int64_t> m_nextTimerId{0};
};

// IO多路复用器接口
class ExportAPI IOMultiplexer
{
public:
    virtual ~IOMultiplexer() = default;
    
    virtual bool Initialize() = 0;
    virtual bool AddFd(int fd, uint32_t events) = 0;
    virtual bool RemoveFd(int fd) = 0;
    virtual bool ModifyFd(int fd, uint32_t events) = 0;
    virtual int Wait(std::vector<std::pair<int, uint32_t>>& activeEvents, int timeoutMs) = 0;
};

class ExportAPI EventLoop 
{
public:
    EventLoop(int threadPoolSize = 4);      // 线程池大小
    ~EventLoop();
    
    EventLoop(const EventLoop&) = delete;
    EventLoop& operator=(const EventLoop&) = delete;
    EventLoop(EventLoop&&) = delete;
    EventLoop& operator=(EventLoop&&) = delete;
    
    void Start();                           // 在新线程运行事件循环，不阻塞当前线程
    void Stop();
    void Run();                             // 在当前线程运行事件循环
    void PostEvent(std::shared_ptr<Event> event);
    
    // 事件处理器相关
    EventHandler::HandlerId RegisterHandler(EventType type, EventHandlerFunc func);
    bool UnregisterHandler(EventType type, EventHandler::HandlerId handlerId);
    
    // IO事件相关
    bool AddIOEvent(int fd, uint32_t events);
    bool RemoveIOEvent(int fd);
    bool ModifyIOEvent(int fd, uint32_t events);
    
    // 定时器相关
    int64_t AddTimer(uint64_t intervalMs, std::function<void(int64_t)> callback, void* userData = nullptr, bool isOneShot = false);
    bool RemoveTimer(int64_t timerId);
    
private:
    void Loop();
    void ProcessPendingEvents();
    uint64_t GetNextTimerTime() const;
    
    std::unique_ptr<PriorityEventQueue> m_queue;
    std::shared_ptr<EventHandler> m_handler;
    std::unique_ptr<ThreadPool> m_threadPool;
    std::unique_ptr<HighResTimer> m_timer;
    std::unique_ptr<IOMultiplexer> m_ioMultiplexer;
    
    std::thread m_thread;
    std::atomic<bool> m_running{false};
};

}  // namespace Tool

#endif // TOOLS_EVENTLOOP_H
